package com.ssmdemo.config;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.ibatis.plugin.Intercepts;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.util.ArrayList;
import java.util.List;

@Configuration
@ComponentScan("com.ssmdemo.controller")
@EnableWebMvc
public class SpringMvcConfig {

    @Bean
    public RequestMappingHandlerAdapter getRequestMappingHandlerAdapter(
            @Qualifier("jsonConverter") MappingJackson2HttpMessageConverter jackson2HttpMessageConverter,
            @Qualifier("stringConverter") StringHttpMessageConverter stringHttpMessageConverter
    ){
        RequestMappingHandlerAdapter requestMappingHandlerAdapter=new RequestMappingHandlerAdapter();
        List<HttpMessageConverter<?>> list=new ArrayList<>();
        list.add(jackson2HttpMessageConverter);
        list.add(stringHttpMessageConverter);
        requestMappingHandlerAdapter.setMessageConverters(list);
        return requestMappingHandlerAdapter;
    }


    @Bean("jsonConverter")
    public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter(@Qualifier("stringConverter") StringHttpMessageConverter stringConverter) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setPrettyPrint(true);
        converter.setPrefixJson(true);
        List<MediaType> list=new ArrayList<>();
        list.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE));
        list.add(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
        list.add(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
        converter.setSupportedMediaTypes(list);
        return converter;
    }

    @Bean("stringConverter")
    public StringHttpMessageConverter getStringHttpMessageConverter(){
        StringHttpMessageConverter stringHttpMessageConverter=new StringHttpMessageConverter();
        stringHttpMessageConverter.setWriteAcceptCharset(false);
        List<MediaType> list=new ArrayList<>();
        list.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE));
        list.add(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
        list.add(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
        stringHttpMessageConverter.setSupportedMediaTypes(list);
        return stringHttpMessageConverter;
    }

}
